package com.xiaoxin.errorDemo.error;

import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 重写错误处理
 */
public class MyErrorController extends BasicErrorController {

    public MyErrorController(ErrorAttributes errorAttributes,
                             ErrorProperties errorProperties) {
        super(errorAttributes, errorProperties);
    }

    /**
     * 构造方法
     *
     * @param errorAttributes    错误属性
     * @param errorProperties    配置属性
     * @param errorViewResolvers 错误解析器
     */
    public MyErrorController(ErrorAttributes errorAttributes,
                             ErrorProperties errorProperties,
                             List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }

    /**
     * 重写错误
     *
     * @param request 请求
     * @param options 参数
     * @return 错误Map
     */
    @Override
    protected Map<String, Object> getErrorAttributes(HttpServletRequest request, ErrorAttributeOptions options) {
        Object extAttribute = request.getAttribute("ext");
        // ↓这是原来的Map
        Map<String, Object> resultMap = super.getErrorAttributes(request, options);
        // ↓这里我们可以添加或者删除一些Key
        resultMap.put("addKey", true);
        resultMap.put("ext", extAttribute);
        return resultMap;
    }
}
